<!-- @author zhengjie -->
<template>
    <div>

        <!-- 传感器模块 -->
        <div class="crate-box" v-if="type == 1">
            <div class="crate-head">
                <img class="head-img" src="@/assets/images/rooms.png" />
                <div class="head-text">{{ title }}</div>
            </div>
            <div class="crate-end">
                <div class="end-state">{{ state == 0 ? '离线' : '在线' }}</div>
                <div class="end-button">
                    <img class="end-li" src="@/assets/images/amend.png" @click="handleUpdateSensor" title="编辑" />
                    <img class="end-li" src="@/assets/images/delete-yellow.png" @click="handleDelete" title="删除" />

                    <!-- <el-popover placement="top-start" popper-class="zt-popper" width="200" trigger="click"
                        class="end-li">
                        <template #reference>
                            <div class="flex-s">
                                <img src="@/assets/images/xs.png" style="margin-right: 0px;">
                            </div>

                        </template>
<template #default>
                            <div class="flex">
                                <div>
                                </div>
                            </div>
                        </template>
</el-popover> -->
                    <el-popover placement="top-start" popper-class="zt-popper" width="280" trigger="click" 
                        @after-enter="sensorAttributeOpen(id)" @hide="sensorAttributeClose">
                        <template #reference>
                            <div class="flex-s">
                                <img src="@/assets/images/xs.png" style="margin-right: 0px;" title="状态" >
                            </div>
                        </template>
                        <template v-show="popoverOpen" #default>
                            <div class="flex message-popup">
                                <div>
                                    <div v-for="(item, index) in sensorAttribute" :key="index"
                                        style="color: #25CAD5;font-size: 16px;">
                                        {{ item.name }}:{{ item.value }}
                                    </div>
                                </div>
                            </div>
                        </template>
                    </el-popover>
                </div>
            </div>



        </div>

        <!-- 摄像头模块 -->
        <div class="crate-box" v-if="type == 2">
            <div class="crate-head">
                <img class="head-img" src="@/assets/images/nodeCamera.png" />
                <div class="head-text">{{ title }}</div>
            </div>
            <div class="crate-end">
                <div class="end-state">{{ state == 0 ? '离线' : '在线' }}</div>
                <div class="end-button">
                    <img class="end-li" src="@/assets/images/amend.png" @click="handleUpdateCamera" title="编辑" />
                    <img class="end-li" src="@/assets/images/delete-yellow.png" @click="handleDelete" title="删除" />
                    <jessibuca-bto :id="id" title="预览" ></jessibuca-bto>
                    <!-- <el-popover placement="left-end" :width="20" trigger="click" :visible-arrow="false">
                        <div slot="reference" class="result flex-center">
                            <div class="flv-player-button-crate" @click="flvButton(scope.row)">
                                <div class="flex-s">
                                <img src="@/assets/images/node-full.png" style="margin-right: 0px;">
                                
                            </div>
                            </div>
                        </div>
                        <div slot="default" class="flv-player-popover"> <flv-player class="flv-player" controls autoplay
                                :muted="true" :source="flv.src" :type="flv.type" />
                        </div>
                    </el-popover> -->


                </div>
            </div>



        </div>
        <!-- 天线模块 -->
        <div class="crate-box" v-if="type == 3">
            <div class="crate-head">
                <img class="head-img" src="@/assets/images/and.png" />
                <div class="head-text">{{ title }}</div>
            </div>
            <div class="crate-end">
                <div class="end-state">{{ state === 0 ? '离线' : '在线' }}</div>
                <div class="end-button">
                    <img class="end-li" src="@/assets/images/amend.png" @click="handleUpdateAntenna" title="编辑" />
                    <img class="end-li" src="@/assets/images/delete-yellow.png" @click="handleDelete" title="删除" />
                </div>
            </div>



        </div>

        <!-- 修改模块 -->
        <!-- 传感器 -->
        <right-dialog title="修改传感器" :visible="open.sensor" @closeDialog="cancel">
            <template v-slot:default>
                <div class="zt-dialog-solt">
                    <el-form ref="formSensor" :model="setAllForm" label-width="120px">
                        <el-form-item label="传感器名称:">
                            <div class="flex">
                                <el-input class="blue-input" v-model="setAllForm.sensor.sensorName"
                                    placeholder="请输入传感器名称" />
                                <el-button class="bt-blue " @click="submitFormSensor" style="margin-left: 10px; ">{{
            title
                ==
                '添加天线' ? '添加' :
                '确定'
        }}</el-button>
                            </div>
                        </el-form-item>
                        <el-form-item label="传感器类型:" prop="inoutType">
                            <div class="flex">
                                <el-select v-model="setAllForm.sensor.inoutType" filterable placeholder="传感器类型"
                                    class="zt-input rihgt-m5" style="width: 240px;font-weight: 600;">
                                    <el-option v-for="item in  dict.type.inout_type" :key="item.value"
                                        :label="item.label" :value="item.value" />
                                </el-select>
                                <el-form-item label="所属地:" prop="locatedAddress">
                                    <el-select v-model="setAllForm.sensor.locatedAddress" filterable placeholder="所属地"
                                        class="zt-input-min rihgt-m5" style="width: 120px;font-weight: 600;">
                                        <el-option v-for="item in  dict.type.located_address" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                                <!-- <el-form-item label="入网状态:" v-if="isNet == 0" v-model="setAllForm.sensor.isNet">
                                    <el-select filterable v-model="setAllForm.sensor.isNet"
                                        class="zt-input-min rihgt-m5">
                                        <el-option :key="0" label="未入网" value="0" />
                                        <el-option :key="1" label="已入网" value="1" />
                                    </el-select>
                                </el-form-item> -->

                            </div>
                        </el-form-item>

                        <el-form-item label="开关:">
                            <el-switch v-model="setAllForm.sensor.isPower" active-color="#13ce66" active-value="1"
                                inactive-value="0">
                            </el-switch>
                        </el-form-item>
                        <el-form-item label="备注:" prop="remark">
                            <el-input v-model="setAllForm.sensor.remark" type="textarea" placeholder="请输入内容" />
                        </el-form-item>
                    </el-form>

                </div>
            </template>
        </right-dialog>



        <right-dialog title="修改摄像头" :visible="open.camera" @closeDialog="cancel">
            <template v-slot:default>
                <div class="zt-dialog-solt">
                    <el-form ref="formCamera" :model="setAllForm.camera" :rules="rules.camera" label-width="125px">
                        <el-form-item label="摄像头名称:" prop="cameraName">
                            <div class="flex">
                                <el-input class="blue-input" v-model="setAllForm.camera.cameraName"
                                    placeholder="请输入摄像头名称" />
                                <el-button class="bt-blue " @click="submitFormCamera"
                                    style="margin-left: 10px; ">确定</el-button>
                            </div>
                        </el-form-item>

                        <el-form-item label="所属地:" prop="locatedAddress">
                            <div class="flex">
                                <el-select v-model="setAllForm.camera.locatedAddress" filterable placeholder="所属地"
                                    class="zt-input-min rihgt-m5" style="width: 120px;font-weight: 600;">
                                    <el-option v-for="item in  dict.type.located_address" :key="item.value"
                                        :label="item.label" :value="item.value" />
                                </el-select>

                                <el-form-item label="摄像头类型:" prop="inoutType">
                                    <el-select v-model="setAllForm.camera.inoutType" filterable placeholder="摄像头类型"
                                        class="zt-input-min rihgt-m5" style="width: 120px;font-weight: 600;">
                                        <el-option v-for="item in  dict.type.inout_type" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>

                            </div>
                        </el-form-item>


                        <el-form-item label="云曜项目ID:" prop="projectId">
                            <div class="flex">
                                <el-input v-model="setAllForm.camera.projectId" filterable placeholder="云曜项目ID"
                                    class="zt-input-min rihgt-m5" style="width: 149px;font-weight: 600;">
                                </el-input>


                                <el-form-item label="云曜设备序列号:" prop="deviceSerial">
                                    <el-input v-model="setAllForm.camera.deviceSerial" filterable
                                        placeholder="序列号" @input="handleInput" :maxlength="9" ref="addressInput"
                                        class="zt-input-min rihgt-m5" style="width: 120px;font-weight: 600;">
                                    </el-input>
                                </el-form-item>

                                <el-form-item label="设备通道:">
                                    <el-input v-model="setAllForm.camera.channelNo" filterable placeholder="设备通道"
                                        :maxlength="9" ref="addressInput" class="zt-input-min rihgt-m5"
                                        style="width: 120px;font-weight: 600;">
                                    </el-input>
                                </el-form-item>

                            </div>
                        </el-form-item>

                        <el-form-item label="摄像头流地址:">
                            <el-input v-model="setAllForm.camera.cameraUrl" type="textarea" placeholder="摄像头流地址" />
                        </el-form-item>
                        <el-form-item label="备注:">
                            <el-input v-model="setAllForm.camera.remark" type="textarea" placeholder="请输入内容" />
                        </el-form-item>
                    </el-form>

                </div>
            </template>
        </right-dialog>

        <!-- 天线 -->
        <right-dialog title="修改天线" :visible="open.antenna" @closeDialog="cancel">
            <template v-slot:default>
                <div class="zt-dialog-solt">
                    <el-form ref="formAntenna" :model="setAllForm" label-width="120px">
                        <el-form-item label="天线名称:">
                            <div class="flex">
                                <el-input class="blue-input" v-model="setAllForm.antenna.antennaName"
                                    placeholder="请输入天线名称" />
                                <el-button class="bt-blue " @click="submitFormAntenna" style="margin-left: 10px; ">{{
            title
                ==
                '添加天线' ? '添加' :
                '确定'
        }}</el-button>
                            </div>
                        </el-form-item>
                        <el-form-item label="类型:" prop="antennaType">
                            <div class="flex">
                                <el-select v-model="setAllForm.antenna.antennaType" filterable placeholder="类型"
                                    class="zt-input-min rihgt-m5">
                                    <el-option v-for="item in  dict.type.antenna_type" :key="item.value"
                                        :label="item.label" :value="item.value" />
                                </el-select>


                                <el-form-item label="所属地:" prop="locatedAddress">
                                    <div class="flex">

                                        <el-select v-model="setAllForm.antenna.locatedAddress" filterable
                                            placeholder="所属地" class="zt-input-min rihgt-m5"
                                            style="width: 120px;font-weight: 600; ">
                                            <el-option v-for="item in  dict.type.located_address" :key="item.value"
                                                :label="item.label" :value="item.value" />
                                        </el-select>
                                    </div>
                                </el-form-item>
                            </div>

                        </el-form-item>
                        <el-form-item label="室内外:" prop="inoutType">
                            <el-select v-model="setAllForm.antenna.inoutType" filterable placeholder="室内外"
                                class="zt-input rihgt-m5" style="width: 240px;font-weight: 600;">
                                <el-option v-for="item in  dict.type.inout_type" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="备注:" prop="remark">
                            <el-input v-model="setAllForm.antenna.remark" type="textarea" placeholder="请输入内容" />
                        </el-form-item>
                    </el-form>

                </div>

            </template>
        </right-dialog>


    </div>
</template>

<script>
import RightDialog from "@/components/TZ/RightDialog"
import { getSensor, delSensor, updateSensor } from "@/api/business/sensor";
import { getCamera, delCamera, updateCamera } from "@/api/business/camera";
import { getAntenna, delAntenna, updateAntenna } from "@/api/business/antenna";
import flvPlayer from "@/components/TZ/CameraVideo/index.js";
// import JessibucaBto from "@/components/TZ/JessibucaBto";
import JessibucaBto from "@/components/TZ/JessibucaBtoId";


export default {
    name: 'Crate',
    dicts: ['sensor_code', 'located_address', 'sensor_type', 'antenna_type', 'inout_type'],
    components: { RightDialog, flvPlayer, JessibucaBto },
    props: {
        title: {//全部数据
            type: String,
            default: "新疆基地-机箱1设备"
        },
        id: {
            type: Number,
        },
        state: {//选中数据 
            type: String,
        },
        type: {// 1-传感器 2-摄像头 3-天线 
            type: String,

        },


    },
    watch: {

    },
    data() {
        return {
            value: [],
            setAllForm: {//修改
                sensor: null,//天线模块
                camera: null,//摄像头模块
                antenna: null,
            },
            open: {
                sensor: false,
                camera: false,
                antenna: false,
            },
            flv: {
                type: 'flv',
                src: '',
            },
            rules: {
                sensor: null,//天线模块
                camera: {
                    cameraName: [
                        { required: true, message: "摄像头名称不能为空", trigger: "change" }
                    ],
                    cameraType: [
                        { required: true, message: "摄像头类型不能为空", trigger: "change" }
                    ],
                    cameraAttribute: [
                        { required: true, message: "摄像头属性不能为空", trigger: "change" }
                    ],
                    cameraUrl: [
                        { required: true, message: "摄像头流地址能为空", trigger: "change" }
                    ],
                    deviceSerial: [
                        { required: true, message: "设备序列号不能为空", trigger: "change" }
                    ],
                    projectId: [
                        { required: true, message: "云曜项目ID不能为空", trigger: "change" }
                    ],
                    locatedAddress: [
                        { required: true, message: "所属地不能为空", trigger: "change" }
                    ],
                    status: [
                        { required: true, message: "状态不能为空", trigger: "change" }
                    ],
                    inoutType: [
                        { required: true, message: "摄像头类型不能为空", trigger: "change" }
                    ],
                },//摄像头模块
                antenna: null,
            },
            sensorAttribute: null,
            popoverOpen: null,

        }
    },
    created() {
        this.reset();
    },
    methods: {
        sensorAttributeClose() {//清除传感器属性
            this.sensorAttribute = {};
            this.popoverOpen = false;
        },
        sensorAttributeOpen(sensorId) {//显示传感器属性
            console.log("sensorId:", sensorId);
            getSensor(sensorId).then(response => {
                this.sensorAttribute = this.parseJsonString(response.data);
                this.popoverOpen = true;
            })

            // console.log(this.sensorAttribute);
        },
        //将字符串解析成对象
        parseJsonString(jsonString) {

            const string = JSON.parse(jsonString.sensorAttribute);
            const sensorCodeArray = this.dict.type.sensor_code;
            console.log(JSON.stringify(sensorCodeArray));
            let resultArray = sensorCodeArray
                .filter(sensor => string.hasOwnProperty(sensor.value))
                .map(sensor => ({ name: sensor.label, value: parseInt(string[sensor.value]) / 10 }));
            resultArray.push({ name: '上次获取时间', value: jsonString.updateTime })

            // const arr = [
            //   {"name":"W湿度","value":62.9},{"name":"N温度","value":8.3},{"name":"N湿度","value":61.5},
            //   {"name":"风速","value":60},{"name":"风向","value":'西北风'},{"name":"雨量","value":61.5},
            //   {"name":"W温度","value":80},{"name":"风力","value":'100'}
            // ]

            // const arrs = [
            //   {"name":"室外湿度","value":"62.9Pa","type":0},{"name":"室内温度","value":"88.3℃","type":1},{"name":"室内湿度","value":"61.Pa","type":0},
            //   {"name":"风速","value":"60m/s","type":0},{"name":"风向","value":'西北风',"type":0},{"name":"雨量","value":"61.5mm","type":0},
            //   {"name":"室外温度","value":"70℃","type":0},{"name":"风力","value":'100级',"type":0}
            // ]

            // 将arr数组转为arrs数组，w表示室外，n表示室内，温度的单位是℃，雨量的单位是mm，湿度的单位是Pa，风力的单位是级...type的值为0表示正常，当温度大于80的时候为异常type的值应该为1



            return this.transformArray(resultArray);

        },
        transformArray(resultArray) {
            return resultArray.map(item => {
                let newItem = { name: '', value: '', type: 0 };

                // Set name and value
                if (item.name.includes('W')) {
                    newItem.name = '室外' + item.name.substring(1);
                } else if (item.name.includes('N')) {
                    newItem.name = '室内' + item.name.substring(1);
                } else {
                    newItem.name = item.name;
                }

                newItem.value = item.value;

                // Set type based on conditions
                if ((item.name.includes('温度') && item.value > 80) || (item.name === '雨量' && item.value > 0)) {
                    newItem.type = 1; // 异常
                }

                // Add units based on name
                if (item.name.includes('温度')) {
                    newItem.value += '℃';
                } else if (item.name.includes('湿度')) {
                    newItem.value += 'Pa';
                } else if (item.name.includes('风速')) {
                    newItem.value += 'm/s';
                } else if (item.name.includes('风力')) {
                    newItem.value += '级';
                } else if (item.name === '雨量') {
                    newItem.value += 'mm';
                }

                return newItem;
            });


        },
        flvButton(row) {
            this.flv.src = row.cameraUrl
        },
        closeDialog() {//关闭回调
            this.$emit("closeDialog", false);
        },
        reset() {
            this.setAllForm.sensor = {
                regionalNodeId: null,
                sensorName: null,
                sensorType: null,
                sensorCode: null,
                remark: null,
            }
            this.setAllForm.camera = {
                cameraId: null,
                cameraName: null,
                cameraType: null,
                cameraAttribute: null,
                locatedAddress: null,
                isUsed: null,
                status: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
                inoutType: null,
                cameraUrl: null,
                projectId: '4613375182210958376',
                deviceSerial: null,
                channelNo: null,
            }

            this.setAllForm.antenna = {
                antennaId: null,
                antennaName: null,
                antennaCode: null,
                antennaType: null,
                locatedAddress: null,
                status: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
                inoutType: null,
            }
        },
        cancel() {
            this.open.sensor = false;
            this.open.camera = false;
            this.open.antenna = false;
        },
        /** 修改天线按钮操作 */
        handleUpdateSensor() {
            const sensorId = this.id
            // this.reset();
            getSensor(sensorId).then(response => {
                this.setAllForm.sensor = response.data;
                this.open.sensor = true;
            });
        },
        handleInput(value) {
            // 移除非法字符
            const formattedValue = value.replace(/[^A-Za-z0-9]/g, '');
            // 限制长度
            if (formattedValue.length > 9) {
                this.form.deviceSerial = formattedValue.substring(0, 9);
            } else {
                this.form.deviceSerial = formattedValue;
            }
        },
        /** 提交天线 */
        submitFormSensor() {
            this.$refs["formSensor"].validate(valid => {
                if (valid) {
                    updateSensor(this.setAllForm.sensor).then(response => {
                        this.$modal.msgSuccess("修改成功");
                        this.open.sensor = false;
                        //这里需要子组件调用父组件重新查询数据
                        this.$emit("getDetailData");

                    });
                }
            });
        },
        /** 修改摄像头按钮操作 */
        handleUpdateCamera() {
            const cameraId = this.id
            // this.reset();
            getCamera(cameraId).then(response => {
                this.setAllForm.camera = response.data;
                this.open.camera = true;
            });
        },
        /** 提交摄像头 */
        submitFormCamera() {
            this.$refs["formCamera"].validate(valid => {
                if (valid) {
                    updateCamera(this.setAllForm.camera).then(response => {
                        this.$modal.msgSuccess("修改成功");
                        this.open.camera = false;
                        //这里需要子组件调用父组件重新查询数据
                        this.$emit("getDetailData");
                    });
                }
            });
        },
        /** 修改天线按钮操作 */
        handleUpdateAntenna() {
            const antennaId = this.id
            // this.reset();
            getAntenna(antennaId).then(response => {
                this.setAllForm.antenna = response.data;
                this.open.antenna = true;
            });
        },
        /** 提交天线 */
        submitFormAntenna() {
            this.$refs["formAntenna"].validate(valid => {
                if (valid) {
                    updateAntenna(this.setAllForm.antenna).then(response => {
                        this.$modal.msgSuccess("修改成功");
                        this.open.antenna = false;
                        //这里需要子组件调用父组件重新查询数据
                        this.$emit("getDetailData");
                    });
                }
            });
        },
        handleDelete() {
            const type = this.type
            const id = this.id

            if (type == 1) {
                this.$modal.confirm('是否确认删除传感器编号为"' + id + '"的数据项？').then(function () {
                    return delSensor(id);
                }).then(() => {
                    this.$modal.msgSuccess("删除成功");
                    this.$emit("getDetailData");
                }).catch(() => { });
            } else if (type == 2) {
                this.$modal.confirm('是否确认删除摄像头编号为"' + id + '"的数据项？').then(function () {
                    return delCamera(id);
                }).then(() => {
                    this.$modal.msgSuccess("删除成功");
                    this.$emit("getDetailData");
                }).catch(() => { });
            } else if (type == 3) {
                this.$modal.confirm('是否确认删除天线编号为"' + id + '"的数据项？').then(function () {
                    return delAntenna(id);
                }).then(() => {
                    this.$modal.msgSuccess("删除成功");
                    this.$emit("getDetailData");
                }).catch(() => { });
            }

        },

    }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.crate-box {
    margin: 5px;
    background-color: #3A4156;
    padding: 2px;
    width: 210px;
    height: 65px;
    border-radius: 5px;
    color: #9A9DAA;

    .crate-head {
        width: 180px;
        margin-left: 5px;
        margin-top: 10px;
        margin-bottom: 8px;
        display: flex;
        justify-content: center;

        .head-img {
            height: 18px;
            width: 18px;
            margin-right: 2px;
        }

        .head-text {
            font-size: 15px;
            width: 140px;
            white-space: nowrap;
            /* 防止文本换行 */
            overflow: hidden;
            /* 超出部分隐藏 */
            text-overflow: ellipsis;
            /* 超出部分显示省略号 */
        }
    }

    .crate-end {
        width: 190px;
        height: 20px;
        margin-left: 8px;
        display: flex;
        justify-content: center;

        .end-state {
            font-size: 15px;
            width: 40px;
            margin-left: 10px;
        }

        .end-button {
            // width: 140px;
            display: flex;
            align-items: center;
            justify-content: center;
            text-align: right;
            margin-left: auto;

            img {
                height: 14px;
                width: 14px;
                cursor: pointer;
                margin-right: 5px;
            }

            .end-li {
                margin-left: auto;
            }

            .end-details {
                font-size: 12px;
            }

            .end-full {
                font-size: 12px;
                color: #2CA6E0;
            }
        }
    }
}
</style>